package com.tony.study.thread.sync;

/**
 * Created with IntelliJ IDEA.
 *
 * @Title: SafeBuyTicket
 * @Auther: 皮蛋布丁
 * @Date: 2021/10/31/20:33
 * @Description: 同步买票
 */
public class SafeBuyTicket {

    public static void main(String[] args) {
        BuyTicket1 station = new BuyTicket1();

        new Thread(station,"苦逼的我").start();
        new Thread(station,"牛逼的你们").start();
        new Thread(station,"可恶的黄牛").start();
    }
}

class BuyTicket1 implements Runnable {

    private int ticketNums = 10;    //票
    boolean flag = true;    //外部停止方法

    @Override
    public void run() {
        //买票
        while (flag) {
            try {
                buy();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    //synchronized 同步方法，锁的是this
    private synchronized void buy() throws InterruptedException {
        //判断是否有票
        if (ticketNums <= 0) {
            flag = false;
            return;
        }
        //模拟延时
        Thread.sleep(100);
        //买票
        System.out.println(Thread.currentThread().getName()+"拿到"+ticketNums--);
    }
}
